﻿using IdentityModel.Client;
using KeYan.Service.Common.Enum;
using KeYan.Service.IRepository.UserLogin;
using KeYan.Service.Model.UserLogin;
using Microsoft.Extensions.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Extensions.Caching.Distributed;

namespace KeYan.Service.Repository.UserLogin
{
    public class UserRepository : IUserRepository
    {
        KeYanContext context = new KeYanContext();
        private IConfiguration _configuration;
        private UserRepository(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        /// <summary>
        /// 账号密码登录,通过ids4进行验证登录
        /// </summary>
        /// <param name="name"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        public async Task<Resilt<string>> GetIdsLogin(string LoginName, string LoginPwd)
        {
            Ids4 ids4Service = new Ids4(_configuration);
            string token = await ids4Service.GetIdsTokenAsync(LoginName, LoginPwd);
            if (string.IsNullOrEmpty(token))
            {
                return Resilt<string>.Error("后台接口授权失败", null, ResultStatus.Error);
            }
            return new Resilt<string>() { State = ResultStatus.Success, Msg = "获取token成功", Data = token };
        }
        /// <summary>
        /// 手机号+密码登录
        /// </summary>
        /// <param name="Tel"></param>
        /// <param name="Pwd"></param>
        /// <returns></returns>
        public async Task<Resilt<int>> PhoneLogin(string Tel, string Pwd)
        {
            var list = context.tb_user_service_info.ToList();
            if (!string.IsNullOrEmpty(Tel) && !string.IsNullOrEmpty(Pwd))
            {
                list = list.Where(s => s.UserTel.Equals(Tel) && s.PassWord.Equals(Pwd)).ToList();
                //判断手机号是否存在
                if (list.Where(s => s.UserTel.Equals(Tel)).Count() < 0)
                {
                    return new Resilt<int> { Data = 0, Msg = "手机号不存在", State = ResultStatus.Error };
                }
                else
                {
                    //判断密码是否正确
                    if (list.Where(s => s.PassWord.Equals(Pwd) && s.UserTel.Equals(Tel)).Count() < 0)
                    {
                        return new Resilt<int> { Data = 0, Msg = "密码错误", State = ResultStatus.Error };
                    }
                    else
                    {
                        return new Resilt<int> { Data = 1, Msg = "登录成功", State = ResultStatus.Success };
                    }
                }
            }
            return new Resilt<int> { Data = 0, Msg = "登录失败", State = ResultStatus.Error };
        }
    }
}
